﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Threading.Tasks;
using WorkerService.Common;
using WorkerService.Data;
using WorkerService.Model.Model;
using WorkerService.Model.Send;

namespace WorkerService.Job
{
    [DisallowConcurrentExecution]
    public class TemperatureJob : IJob
    {
        private readonly ILogger<TemperatureJob> _logger;
        public TemperatureJob(ILogger<TemperatureJob> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 温湿度同步作业
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {

            _logger.LogInformation("温湿度作业开始");

            var time = DateTime.Now.AddHours(-1).ToString("yyyy/MM/dd HH:00:00");

            //温湿度传感器数据
            var sql = $"select  top 1.*   from report_34 where  [Time]>'{time}'  order by  [Time] desc ";
            var data = SqlDBHelper.QueryTable(sql);

            //温湿度传感器
            sql = "select * from Sys_Device  where TableName='report_34'";
            var device = SqlDBHelper.Query<Sys_Device>(sql);

            if (data!=null  &&  data.Rows.Count>0 && device!=null && device.Count>0)
            {
                for (int i = 0; i < device.Count; i++)
                {
                    TemperatureModel model = new TemperatureModel();

                    model.Code = device[i].Code.ToString();
                    model.Name = device[i].Name.ToString();

                    model.Temperature = data.Rows[0][$"temperature_{model.Code}dts"].ToString();
                    model.Humidity = data.Rows[0][$"humidity_{model.Code}dts"].ToString();

                    model.Time= data.Rows[0]["Time"].ToString();
                    model.SiteId = AppConfigurtaionServices.Configuration.GetSection("Site").Value;

                    _logger.LogInformation("温湿度数据上传中：" + JsonConvert.SerializeObject(model));

                    HTTPHelper.Client_Post($"{AppConfigurtaionServices.Configuration.GetSection("Send").Value}Client/TemperatureAccept", JsonConvert.SerializeObject(model), "siteapp.workservice");
                }
            }

            _logger.LogInformation("温湿度作业结束");

            return Task.CompletedTask;
        }
    }





}
